#include "StdAfx.h"
#include ".\event.h"
#include "XLLuaRuntime.h"

Event::Event(void)
{
}

Event::~Event(void)
{
}

int Event::AttachListener(DWORD userdata1,DWORD userdata2,funResultCallBack pfn, const void* pfun )
{
	TSAUTO();
	CallbackNode newNode = {0};
	newNode.pCallBack = pfn;
	newNode.userData1 = userdata1;
	newNode.userData2 = userdata2;
	newNode.luaFunction = pfun;
	m_allCallBack.push_back(newNode);
	TSDEBUG4CXX(" userdata1 : "<<newNode.userData1<<" userData2 : "<< newNode.userData2<<", pfn : "<<pfn << ", pfun : " << pfun);
	return 1;
}

int Event::DetachListener( DWORD userData1, const void* pfun )
{
	TSAUTO();
	std::vector<CallbackNode>::iterator it = m_allCallBack.begin();
	for(; it != m_allCallBack.end(); it++)
	{
		if(it->luaFunction == pfun)
		{
			luaL_unref((lua_State *)(ULONG_PTR)userData1, LUA_REGISTRYINDEX, (int)it->userData2);
			m_allCallBack.erase(it);
			break;
		}
	}
	return 0;
	return 1;
}

void Event::Fire_LuaEvent( const char* pszKey, BSTR bstrParams )
{
	TSAUTO();
	for(size_t i = 0;i<m_allCallBack.size();i++)
	{
		m_allCallBack[i].pCallBack(m_allCallBack[i].userData1,m_allCallBack[i].userData2, pszKey,bstrParams);
	}
}

void Event::Fire_LuaEvent( const char* pszKey, const char* bstrParams )
{
	Fire_LuaEvent( pszKey, A2BSTR(bstrParams));
}
